﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Xml;

namespace StoryFlow
{
    enum MainFormMessageType
    {
        PROJ_NOT_SAVED,
        PROJ_IS_NULL
    }

    public partial class MainForm : Form
    {
        // 主窗口UI线程
        Thread mainFormUIThread = null;
        public MainForm()
        {
            InitializeComponent();
            mainFormUIThread = new Thread(MainFormUIThreadHandler);
            mainFormUIThread.IsBackground = true;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            mainFormUIThread.Start();
        }

        private void MainFormUIThreadHandler()
        {
            while (true)
            {
                // 更新主窗口标题
                try
                {
                    this.Invoke(new Action(() => {
                        if (Common.currentProject != null)
                        {
                            this.Text = "StroyFlow - ";
                            this.Text += Common.currentProject.Title;
                            if (Common.currentProject.ProjectPath != null)
                            {
                                this.Text += " - " + Common.currentProject.ProjectPath;
                            }
                            if (false == Common.currentProject.IsSaved)
                            {
                                this.Text += "[未保存]";
                            }
                        }
                        else
                        {
                            this.Text = "StoryFlow";
                        }
                    }));
                }
                catch (Exception ex)
                {

                }
                
                Thread.Sleep(500);
            }
        }

        private DialogResult ShowMessage(MainFormMessageType messageType, MessageBoxButtons btns = MessageBoxButtons.OK)
        {
            switch(messageType)
            {
                case MainFormMessageType.PROJ_NOT_SAVED:
                    return MessageBox.Show("当前项目没有保存!", "StoryFlow", btns, MessageBoxIcon.Information);
                case MainFormMessageType.PROJ_IS_NULL:
                    return MessageBox.Show("没有打开的项目", "StoryFlow", btns, MessageBoxIcon.Information);
                default:
                    return DialogResult.None;
            }
        }

        private void ConfigProjMenuItem_Click(object sender, EventArgs e)
        {
            // 配置项目
            ProjectConfigForm projForm = new ProjectConfigForm();
            projForm.ShowDialog();
        }

        private void NewProjMenuItem_Click(object sender, EventArgs e)
        {
            bool isOkToNewProj;

            // 判断当前项目是否为空或者已经保存
            isOkToNewProj = Common.currentProject == null || Common.currentProject.IsSaved;
            
            if (isOkToNewProj)
            {
                // 创建新项目
                Common.currentProject = new StoryProject();

                // 项目创建完成后立刻编辑项目信息
                ConfigProjMenuItem_Click(sender, e);
            }
            else
            {
                // 项目没有保存
                ShowMessage(MainFormMessageType.PROJ_NOT_SAVED);
            }
        }

        #region 保存工程
        private void SaveProjMenuItem_Click(object sender, EventArgs e)
        {
            SaveProject();
        }


        private void SaveProject()
        {
            if (Common.currentProject == null)
            {
                ShowMessage(MainFormMessageType.PROJ_IS_NULL);
                return;
            }
            if (Common.currentProject.ProjectPath == "")
            {
                // 项目路径为空，证明还没有被保存过
                string path = SelectSaveProjectFilePath();
                if (path != null)
                {
                    Common.currentProject.ProjectPath = path;
                    SaveProjectToDisk();
                }
                else
                {
                    // 返回的路径为null，证明用户取消了保存，不需要做任何操作
                }
            }
            else
            {
                // 项目路径不为空，判断文件是否存在
                if (File.Exists(Common.currentProject.ProjectPath))
                {
                    // 文件存在，可以继续保存到这个文件
                    SaveProjectToDisk();
                }
                else
                {
                    // 之前保存的项目文件已经不存在，重新选择一个路径
                    string path = SelectSaveProjectFilePath();
                    Common.currentProject.ProjectPath = path;
                    SaveProjectToDisk();
                }
            }
        }
        // 选择新的项目文件路径
        private string SelectSaveProjectFilePath()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "*.storyprj（故事项目）|*.storyprj|*.*（任何文件）|*.*";
            DialogResult result = saveFileDialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                return saveFileDialog.FileName;
            }
            else
            {
                return null;
            }
        }

        private void SaveProjectToDisk()
        {
            XmlDocument proj = Common.currentProject.SerializeToXML();
            proj.Save(Common.currentProject.ProjectPath);
            // 标记当前工程已保存
            Common.currentProject.Saved();
        }

        #endregion

        private void CloseProjMenuItem_Click(object sender, EventArgs e)
        {
            CloseProject();
        }

        private void CloseProject()
        {
            if (Common.currentProject != null && Common.currentProject.IsSaved == false)
            {
                DialogResult res = MessageBox.Show("当前项目未保存，是否保存？", "关闭项目", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (res == DialogResult.Yes)
                {
                    SaveProject();
                    Common.currentProject = null;
                }
                else if (res == DialogResult.No)
                {
                    Common.currentProject = null;
                }
                else
                {
                    return;
                }
            }
            else
            {
                Common.currentProject = null;
            }
        }

        private void SaveAsProjMenuItem_Click(object sender, EventArgs e)
        {
            string newProjPath = SelectSaveProjectFilePath();
            if (newProjPath != null) 
            {
                Common.currentProject.ProjectPath = newProjPath;
                SaveProjectToDisk();
            }
        }

        private void OpenProjMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "*.storyprj(故事项目)|*.storyprj|*.*(任何文件)|*.*";
            
            // 判断当前工程是否保存
            if (Common.currentProject != null && false == Common.currentProject.IsSaved) 
            {
                // 工程不是空的，也没有保存
                DialogResult r = MessageBox.Show("当前项目没有保存，是否保存？", "打开项目", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (r == DialogResult.Yes)
                {
                    SaveProject();
                }
                else if(r == DialogResult.No)
                {
                    // 不保存，什么都不用做
                }
                else
                {
                    // 取消，直接返回
                    return;
                }
            }
            
            DialogResult res = dlg.ShowDialog();
            if (res == DialogResult.OK)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(dlg.FileName);
                Common.currentProject = new StoryProject();
                if (Common.currentProject.LoadFromXML(doc))
                {
                    Common.currentProject.ProjectPath = dlg.FileName;
                }
            }
        }
    }
}
